﻿using ETA.DomainEnum;
using ETA.Dtos;
using ETA.Entity;
using ETA.IService;
using ETA.Web.App_Start;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using System.Web.Providers.Entities;
using System.Web.Script.Serialization;
using System.Web.Security;
namespace ETA.Web.Controllers
{
    public class BaseController : Controller
    {

        protected override void ExecuteCore()
        {
            var langCookie =HttpContext.Request.Cookies["Localization.CultureName"];
            if (langCookie != null)
            {
                Thread.CurrentThread.CurrentCulture = new CultureInfo(langCookie.Value);
                Thread.CurrentThread.CurrentUICulture = new CultureInfo(langCookie.Value);
            }
            base.ExecuteCore();
        }

        #region 属性

        /// <summary>
        /// 当前登录用户
        /// </summary>
        public SimpleUserDto CurrentUser
        {
            get
            {
                return GetCurrentUser();
            }
        }

        #endregion

        #region 方法

        /// <summary>
        /// 返回处理过时间的json
        /// </summary>
        /// <param name="Data"></param>
        /// <returns></returns>
        protected ContentResult JsonWithDate(object Data)
        {
            var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm" };
            return Content(JsonConvert.SerializeObject(Data, Formatting.Indented, timeConverter));
        }

        /// <summary>
        /// 获取当前用户信息
        /// </summary>
        /// <returns></returns>
        public static SimpleUserDto GetCurrentUser()
        {
            SimpleUserDto model = null;
            // 1. 读登录Cookie

            var context = System.Web.HttpContext.Current;
            HttpCookie cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName];
            if (!(cookie == null || string.IsNullOrEmpty(cookie.Value)))
            {
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);

                if (ticket != null && string.IsNullOrEmpty(ticket.UserData) == false)
                { // 3. 还原用户数据
                    model = new JavaScriptSerializer().Deserialize<SimpleUserDto>(ticket.UserData);
                }

            }
            return model;
        }
        #endregion 方法
    }
}
